package cn.didi.feidi.location.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;

import cn.didi.feidi.location.R;
import cn.didi.feidi.location.activity.base.BaseLocationMapActivity;
import cn.didi.feidi.location.util.CommomDialog;
import permissions.dispatcher.NeedsPermission;

/**
 * Created by jinxiong on 2017/7/10.
 */
//定位activity ，定位成功后marker展示当前位置
@permissions.dispatcher.RuntimePermissions
public class LocationMarkerMapActivity extends BaseLocationMapActivity implements GeocodeSearch.OnGeocodeSearchListener {


    private static final String TAG = "LocationMarkerMapActivi";
    /**
     * private static final String TAG = "BaseLocationMapActivity";
     * protected AMap mAMap;//mapView 管理类
     * protected MapView mMapView;
     * protected AMapLocationClient mClient;//定位相关
     * protected AMapLocationClientOption mOption;//定位配置类
     * protected LatLng locationLatLng;
     */

    GeocodeSearch geoCoderSearch;

    private String address = "";
    private String city = "";
    private String district = "";
    private LatLng choosePoint;


    private ImageView ivCenter, ivGoLocal, ivZoomDown, ivZoomUp;
    private Button btnLocalAddress;
    private View vShowAddress;

    private Animation center_pin;

    /**
     * 跳跃
     *
     * @param cameraPosition
     */
    public void goToPlaceByLatLng(CameraPosition cameraPosition) {

        Log.d(TAG, "goToPlaceByLatLng: " + cameraPosition.target.latitude);
        Log.d(TAG, "goToPlaceByLatLng: " + cameraPosition.target.longitude);

        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude),
                10, GeocodeSearch.AMAP);

        geoCoderSearch.getFromLocationAsyn(query);
    }

    @Override
    protected void initView(Bundle saveInstanceState) {

        setContentView(R.layout.act_location_show_marker);
        // view
        ivCenter = (ImageView) this.findViewById(R.id.map_center_icon);
        btnLocalAddress = (Button) this.findViewById(R.id.map_center_point_tx);
        ivGoLocal = (ImageView) this.findViewById(R.id.get_current_location);
        ivZoomUp = (ImageView) this.findViewById(R.id.zoomLevelUp);
        ivZoomDown = (ImageView) this.findViewById(R.id.zoomLevelDown);
        vShowAddress = this.findViewById(R.id.map_center_view);

        btnLocalAddress.setClickable(true);
        vShowAddress.setClickable(true);
        btnLocalAddress.setEnabled(true);
        vShowAddress.setEnabled(true);

        mMapView = (MapView) this.findViewById(R.id.map_view);

        // 初始化标点动画
        centerIconAnimation();
    }

    @Override
    protected void initVariables() {

        mAMap = mMapView.getMap();
        geoCoderSearch = new GeocodeSearch(this);
        initMapView();
    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    public void getPermission() {

    }

    /**
     * 隐藏地图缩放按钮
     */
    public void initMapView() {
        UiSettings mUiSettings = mAMap.getUiSettings();
        mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);// 设置地图logo显示在左下方
        mUiSettings.setZoomControlsEnabled(false); //是否显示缩放按钮
        mUiSettings.setCompassEnabled(false); //是否显示指南针
        mUiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮

        mAMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                ivCenter.startAnimation(center_pin);
                goToPlaceByLatLng(cameraPosition);
            }
        });
    }

    @Override
    protected void loadData() {
        LocationMarkerMapActivityPermissionsDispatcher.getPermissionWithCheck(this);
        mClient.startLocation();
        makeToast("开始定位");
    }

    @Override
    protected void addListener() {
        geoCoderSearch.setOnGeocodeSearchListener(this);

        vShowAddress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                sendData();
            }
        });
        btnLocalAddress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                sendData();
            }
        });
        ivGoLocal.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!isMultiplicationClick()) {
                    makeToast("正在定位中，请稍后");
//                btnLocalAddress.setText("请稍后...");
                    ivCenter.startAnimation(center_pin);
                    // 获取当前位置
                    mClient.startLocation();
                } else {
                    Log.d(TAG, "点击太快了");
                }
            }
        });
        ivZoomUp.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                float zoomLevel = mAMap.getCameraPosition().zoom;
                float a = mAMap.getMaxZoomLevel();
                if (zoomLevel < a) {
                    mAMap.animateCamera(CameraUpdateFactory.zoomIn());
                    ivZoomDown.setEnabled(true);
                } else {
                    ivZoomUp.setEnabled(false);
                    // makeToast("已缩至最小！");
                }
            }
        });
        ivZoomDown.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                float zoomLevel = mAMap.getCameraPosition().zoom;
                float a = mAMap.getMinZoomLevel();
                if (zoomLevel > a) {
                    mAMap.animateCamera(CameraUpdateFactory.zoomOut());
                    ivZoomUp.setEnabled(true);
                } else {
                    ivZoomDown.setEnabled(false);
                    // makeToast("已放至最大！");
                }
            }
        });
    }

    /**
     * @param marker 将要展示infoWindow的marker
     * @return 自定义的view
     */
    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    /***
     *
     * @param marker 被点击的marker
     * @return
     */
    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            Log.d(TAG, "onLocationChanged: " + aMapLocation.getLatitude());
            Log.d(TAG, "onLocationChanged: " + aMapLocation.getLongitude());

            makeToast("定位成功");

            mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()), 15));

            this.city = aMapLocation.getCity();
            this.district = aMapLocation.getDistrict();
            this.address = aMapLocation.getAddress().substring(aMapLocation.getAddress().indexOf(district) + district.length());

            this.choosePoint = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());

            btnLocalAddress.setText(address);
        } else {
            // 服务端定位失败，请您检查是否禁用获取位置信息权限，尝试重新请求定位。
            // makeToast("无法获取有效定位依据，定位失败，请检查运营商网络或者wifi网络是否正常开启，尝试重新请求定位。");
            reLocationDialog("定位失败，请检查运营商网络或者wifi网络是否正常开启");
        }
    }

    @Override
    public void onBackPressed() {
        sendData();
        super.onBackPressed();
    }

    /**
     * 发送数据
     */
    public void sendData() {
        Log.d(TAG, "sendData: " + choosePoint);
        if (choosePoint != null) {
            Intent intent = new Intent();

            intent.putExtra("address", address);
            if (choosePoint != null) {
                intent.putExtra("latLng", choosePoint);
            }
            intent.putExtra("city", city);
            intent.putExtra("district", district);

            setResult(3, intent);//对应PersonAddReceiveAddressFragment 中的result
            finish();
        } else {
            makeToast("根据您的网络情况,请再稍微移动地图后操作");
        }
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

        RegeocodeAddress address = regeocodeResult.getRegeocodeAddress();

        Log.d(TAG, "onRegeocodeSearched: " + address.getFormatAddress());
        Log.d(TAG, "onRegeocodeSearched: " + regeocodeResult.getRegeocodeQuery().getPoint().getLatitude());
        Log.d(TAG, "onRegeocodeSearched: " + regeocodeResult.getRegeocodeQuery().getPoint().getLongitude());

        this.city = address.getCity();
        this.district = address.getDistrict();
        this.address = address.getFormatAddress().substring(address.getFormatAddress().indexOf(district) + district.length());

        this.choosePoint = new LatLng(regeocodeResult.getRegeocodeQuery().getPoint().getLatitude(), regeocodeResult.getRegeocodeQuery().getPoint().getLongitude());

        btnLocalAddress.setText(this.address);
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    /**
     * 地图标志图标动画
     *
     * @author chaoking
     */
    private void centerIconAnimation() {
        center_pin = AnimationUtils.loadAnimation(this, R.anim.anim_center_pin);
        center_pin.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {

            }

            @Override
            public void onAnimationRepeat(Animation arg0) {

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                Animation center_pin2 = AnimationUtils.loadAnimation(LocationMarkerMapActivity.this, R.anim.anim_center_pin2);
                ivCenter.startAnimation(center_pin2);
            }
        });
    }

    private void reLocationDialog(String text) {
        new CommomDialog(this, R.style.dialog, text, new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    mClient.startLocation();
                    makeToast("开始定位");
                    dialog.dismiss();
                } else {
                    finish();
                    dialog.dismiss();
                }
            }
        }, false, true).setNegativeButton("返回").setPositiveButton("重新定位").show();
    }

    /**
     * @param text
     */
    public void makeToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    private long curClickTimeMillis = 0;

    /**
     * 是否点击了多次 小于1秒当作是一次点击了
     **/
    protected boolean isMultiplicationClick() {
        if (curClickTimeMillis == 0) {
            curClickTimeMillis = System.currentTimeMillis();
            return false;
        }
        boolean rs = System.currentTimeMillis() - curClickTimeMillis < 1000;
        curClickTimeMillis = System.currentTimeMillis();
        return rs;
    }
}
